package zzh.com.kangkenuo;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzh
 * @Name:
 * @Description:
 * @date
 * @time
 * @copyright
 */
public class WXUtlis {


    /**
     * 获取微信accesstoken https://api.weixin.qq.com/sns/oauth2/
     * access_token?appid=APPID
     * &secret=SECRET&code=CODE&grant_type=authorization_code
     */
    public static void getAccessToken(String code) {
        String getATUrl = new String();
        getATUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + Constants.APP_ID + "&secret=" + Constants.APP_SECRET + "&code="
                + code + "&grant_type=authorization_code";

        AsyncTask<String, Integer, HashMap<String, String>> getTokenTask = new AsyncTask<String, Integer, HashMap<String, String>>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected HashMap<String, String> doInBackground(String... params) {
                try {
                    String resultString = getInput2String(params[0]);
                    // 对sb进行jsonObject
                    JSONObject jsonObject;
                    jsonObject = new JSONObject(resultString);
                    String access_token_code = (String) jsonObject
                            .get("access_token");
                    String openId = jsonObject.getString("openid");
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("access_token", access_token_code);
                    hashMap.put("openid", openId);
                    return hashMap;
                } catch (JSONException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
                return null;
            }

            @Override
            protected void onPostExecute(HashMap<String, String> result) {
                super.onPostExecute(result);

                String access_token = result.get("access_token");
                String openid = result.get("openid");

                Log.e("access", access_token + ":" + openid);
                getUID(access_token, openid);
            }
        };
        getTokenTask.execute(getATUrl);
    }

    /*
     * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=
     * OPENID 获取微信个人信息
     */
    private static void getUID(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token + "&openid=" + openid;

        AsyncTask<String, String, JSONObject> getUIDtask = new AsyncTask<String, String, JSONObject>() {
            @Override
            protected JSONObject doInBackground(String... params) {
                String resultString = getInput2String(params[0]);
                // 对sb进行jsonObject
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(resultString);
                    return jsonObject;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(JSONObject result) {
                Log.e("TAG", result.toString());
                //调用后端接口
                Map<String, String> appParams = new HashMap<>();
                /**
                 * 添加参数
                 */
                appParams.put("code", "0038cca697322872459396a417bf284f");

                // appParams.put("unionid", unionid);
                //appParams.put("userInfo", wxuser);
               // PublicRequest.doPostRequest(Constants.API_WXLOGIN, appParams, "接受数据类型");
            }
        };
        getUIDtask.execute(url);
    }

    /**
     * 访问微信连接返回inputstream工具类
     *
     * @param url1
     * @return
     */
    @SuppressWarnings("finally")
    public static String getInput2String(String url1) {
        InputStream is = null;
        BufferedReader bf = null;
        String result = null;
        try {
            URL url = new URL(url1);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            if (httpConn != null) {
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(3000);
                int resCode = httpConn.getResponseCode();
                if (resCode == 200) {
                    is = httpConn.getInputStream();
                    if (is != null) {
                        bf = new BufferedReader(new InputStreamReader(is));
                        StringBuffer sb = new StringBuffer();
                        String ALine = null;
                        while ((ALine = bf.readLine()) != null) {
                            sb.append(ALine);
                        }
                        result = sb.toString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bf != null) {
                try {
                    bf.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

}
